package com.yujing.yview

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.util.Log
import android.widget.DatePicker
import android.widget.LinearLayout
import android.widget.NumberPicker
import androidx.core.content.ContextCompat
import com.yujing.yview.base.YBaseDialog
import com.yujing.yview.databinding.DialogSelectorBinding

/**
 * 选择对话框
 */
/*用法
YNumberPicker.TextSize = 16

val name = arrayOf("全部", "1号线", "2号线", "3号线", "4号线", "5号线", "6号线", "7号线", "8号线", "9号线")
val dialog = YSelectorDialog(this, *name)
dialog.title = "请选择收购线"
dialog.setOnValueListener { index, value ->
    dialog.dismiss()
    //逻辑操作
}
dialog.show()
 */
class YSelectorDialog(activity: Activity, isCancelable: Boolean, vararg values: String?) : YBaseDialog<DialogSelectorBinding>(activity, R.layout.dialog_selector, android.R.style.Theme_Material_Dialog_NoActionBar) {
    private var onValueChangeListener: NumberPicker.OnValueChangeListener? = null
    private var onValueListener: ((Int, String?) -> Unit)? = null
    private var index = 0 //当前位置
    private var value: String? = null
    var title = "请选择"
    var btNameOK = "确　定"
    var btNameCancel = "取　消"

    //分割线颜色，安卓10以上无效
    var dividerColor = Color.parseColor("#FFFFFF")
        private set

    //分割线高度px，安卓10以上无效
    val dividerHeight = 2

    //文字大小比例
    var textSizeScale = 1.0f

    //初始化完成
    var initCompleteListener: ((DialogSelectorBinding) -> Unit)? = null

    constructor(activity: Activity) : this(activity, true, null)
    constructor(activity: Activity, vararg values: String?) : this(activity, true, *values)

    var values: Array<out String?>? = null

    init {
        cancel = isCancelable
        this.values = values
        if (this.values == null || this.values!!.isEmpty()) {
            this.values = arrayOf("空")
        }
        fullscreen = true
        fillColor = ContextCompat.getColor(activity, R.color.fill_background)
    }

    //确定事件
    fun confirm() {
        onValueListener?.invoke(index, value)
    }

    override fun init() {
        binding.tvTitle.text = title
        //格式化，可以替换内容
        binding.numberPicker.setFormatter(null)
        binding.numberPicker.setOnValueChangedListener { picker, oldVal, newVal ->
            onValueChangeListener?.onValueChange(picker, oldVal, newVal)
            value = values!![newVal]
            index = newVal
        }
        binding.numberPicker.setOnScrollListener(null)
        binding.numberPicker.displayedValues = values
        binding.numberPicker.maxValue = values!!.size - 1
        binding.numberPicker.minValue = 0
        binding.numberPicker.value = index
        //设置文字颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) binding.numberPicker.textColor = ContextCompat.getColor(context, R.color.text_color1)
        //设置分割线颜色
        setDividerColor(binding.numberPicker)
        //设置分割线高度
        setNumberPickerDivider(binding.numberPicker)
        //设置为对当前值不可编辑
        binding.numberPicker.descendantFocusability = DatePicker.FOCUS_BLOCK_DESCENDANTS
        //这里设置为不循环显示，默认值为true
        binding.numberPicker.wrapSelectorWheel = false
        value = values!![0]
        binding.btConfirm.text = btNameOK
        binding.btCancel.text = btNameCancel
        binding.btConfirm.setOnClickListener { v -> confirm() }
        binding.btCancel.setOnClickListener { v -> dismiss() }

        //---------------------------缩放---------------------------
        //设置文字放大缩小倍数
        binding.tvTitle.textSize = px2sp(binding.tvTitle.textSize.toInt()) * textSizeScale
        binding.btCancel.textSize = px2sp(binding.btCancel.textSize.toInt()) * textSizeScale
        binding.btConfirm.textSize = px2sp(binding.btConfirm.textSize.toInt()) * textSizeScale
        //按钮高度缩放
        val lp = binding.llBt.layoutParams as LinearLayout.LayoutParams
        lp.height = (lp.height * textSizeScale).toInt()
        binding.llBt.layoutParams = lp
        //---------------------------缩放---------------------------
        initCompleteListener?.invoke(binding)
    }

    //向上滚动一格
    fun scrollUp() {
        if (index > 0) index-- else return
        binding.numberPicker.value = index
        onValueChangeListener?.onValueChange(binding.numberPicker, index + 1, index)
        value = values!![index]
    }

    //向下滚动一格
    fun scrollDown() {
        if (index < values!!.size - 1) index++ else return
        binding.numberPicker.value = index
        onValueChangeListener?.onValueChange(binding.numberPicker, index - 1, index)
        value = values!![index]
    }

    /**
     * 设置picker分割线的颜色
     */
    fun setDividerColor(numberPicker: NumberPicker?) {
        val pickerFields = NumberPicker::class.java.declaredFields
        for (pf in pickerFields) {
            if (pf.name == "mSelectionDivider") {
                pf.isAccessible = true
                try {
                    pf[numberPicker] = ColorDrawable(dividerColor)
                } catch (e: Exception) {
                    Log.e("错误", "设置分割线颜色", e)
                }
                break
            }
        }
    }

    /**
     * 设置picker分割线的宽度(分割线的粗细)
     */
    fun setNumberPickerDivider(picker: NumberPicker?) {
        val fields = NumberPicker::class.java.declaredFields
        for (f in fields) {
            if (f.name == "mSelectionDividerHeight") {
                f.isAccessible = true
                try {
                    f[picker] = dividerHeight
                } catch (e: Exception) {
                    Log.e("错误", "设置分割线的宽度", e)
                }
                break
            }
        }
    }

    fun setDefaultValue(defaultValue: Int) {
        index = defaultValue
    }

    fun setOnValueChangeListener(onValueChangeListener: NumberPicker.OnValueChangeListener?) {
        this.onValueChangeListener = onValueChangeListener
    }

    fun setOnValueListener(onValueListener: ((Int, String?) -> Unit)?) {
        this.onValueListener = onValueListener
    }

    fun setDividerColor(dividerColor: Int) {
        this.dividerColor = dividerColor
    }
}